﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml;
using C1.WPF;
using Microsoft.Win32;
using Model.Modules;
using SteelDetection.UIControl;
using Utility;
using ViewModel;

namespace SteelDetection
{
    /// <summary>
    /// PageImageView.xaml 的交互逻辑
    /// </summary>
    public partial class PageImageView : Page
    {
        public PageImageView()
        {
            InitializeComponent();

            Loaded += Page_Loaded;

        }


        List<ScrollViewer> scrollViewers = new List<ScrollViewer>();

        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            for (int i = 0; i < 20000; i++)
            {
                clist.Items.Add(new ListViewItem());
            }
            //Diff:根据各项目的相机生成的列表同步
            scrollViewers.Add(VisualTreeHelper.GetChild(VisualTreeHelper.GetChild(this.surfaceview1, 0), 0) as ScrollViewer);
            scrollViewers.Add(VisualTreeHelper.GetChild(VisualTreeHelper.GetChild(this.imageview1, 0), 0) as ScrollViewer);
            scrollViewers.Add(VisualTreeHelper.GetChild(VisualTreeHelper.GetChild(this.imageview2, 0), 0) as ScrollViewer);
            scrollViewers.Add(VisualTreeHelper.GetChild(VisualTreeHelper.GetChild(this.imageview3, 0), 0) as ScrollViewer);
            scrollViewers.Add(VisualTreeHelper.GetChild(VisualTreeHelper.GetChild(this.imageview4, 0), 0) as ScrollViewer);
            scrollViewers.Add(VisualTreeHelper.GetChild(VisualTreeHelper.GetChild(this.imageview5, 0), 0) as ScrollViewer);
            scrollViewers.Add(VisualTreeHelper.GetChild(VisualTreeHelper.GetChild(this.imageview6, 0), 0) as ScrollViewer);
            scrollViewers.Add(VisualTreeHelper.GetChild(VisualTreeHelper.GetChild(this.imageview7, 0), 0) as ScrollViewer);
            scrollViewers.Add(VisualTreeHelper.GetChild(VisualTreeHelper.GetChild(this.imageview8, 0), 0) as ScrollViewer);
            for (int i = 0; i < scrollViewers.Count; i++)
            {
                scrollViewers[i].Name = "sv" + i;
            }
            foreach (var scrollViewer in scrollViewers)
            {
                scrollViewer.ScrollChanged += (s, a) =>
                {
                    var scrollViewer1 = s as ScrollViewer;
                    var scrollViewer2 = scrollViewers.Where(sv => sv.Name != scrollViewer1.Name);
                    foreach (var sv in scrollViewer2)
                    {
                        sv.ScrollToVerticalOffset(scrollViewer1.VerticalOffset);

                    }
                };
            }
            scrollViewers[3].ScrollChanged += PageImageView_ScrollChanged;

            IsLoadctl.IsEnabled = true;

            //在停止刷新时，更改  主图中显示的最新图像=>当前选中的历史图像
            (this.DataContext as VM_PageImageView).RequestUpdateCurrentHistoryImage += (s, ee) =>
            {
                var selectindex = this.surfaceview1.SelectedIndex;
                this.surfaceview1.SelectedIndex = -1;
                this.surfaceview1.SelectedIndex = selectindex;
            };

            new UserControl[] { topSurfaceViewer, bottomSurfaceViewer }.All((uc) =>
            {
                var scrollveiwer = (ScrollViewer)uc.Content;
                scrollveiwer.ScrollToHorizontalOffset(700);
                return true;
            });
            var viewerinfos = (XmlElement)SysConfig.GetInstance().SelectSingleNode("/sysconfig/view/PageImageView/viewerlist");
            if (viewerinfos != null && (viewerinfos as XmlElement).GetAttribute("needSetting") == "true")
            {
                var viewerlist = viewerinfos.ChildNodes.Cast<XmlElement>().ToList();
                var topviewerlist = ((topSurfaceViewer.Content as ScrollViewer).Content as StackPanel).Children.Cast<UCImgViewer>().ToList();
                topviewerlist[0].Width = int.Parse(viewerlist.Where(v => v.GetAttribute("name") == "top1").FirstOrDefault()?.GetAttribute("width"));
                topviewerlist[1].Width = int.Parse(viewerlist.Where(v => v.GetAttribute("name") == "top2").FirstOrDefault()?.GetAttribute("width"));

                var bottomscrollviewerlist = ((bottomSurfaceViewer.Content as ScrollViewer).Content as StackPanel).Children.Cast<ScrollViewer>().ToList();
                bottomscrollviewerlist[0].Width = int.Parse(viewerlist.Where(v => v.GetAttribute("name") == "bottom1").FirstOrDefault()?.GetAttribute("width")) - 200;
                bottomscrollviewerlist[0].ScrollToHorizontalOffset(135);
                bottomscrollviewerlist[1].Width = int.Parse(viewerlist.Where(v => v.GetAttribute("name") == "bottom2").FirstOrDefault()?.GetAttribute("width")) - 140;
                bottomscrollviewerlist[1].ScrollToHorizontalOffset(70);
                bottomscrollviewerlist[2].Width = int.Parse(viewerlist.Where(v => v.GetAttribute("name") == "bottom3").FirstOrDefault()?.GetAttribute("width")) - 200;
                bottomscrollviewerlist[2].ScrollToHorizontalOffset(94);
                (bottomscrollviewerlist[0].Content as UCImgViewer).Width = int.Parse(viewerlist.Where(v => v.GetAttribute("name") == "bottom1").FirstOrDefault()?.GetAttribute("width"));
                (bottomscrollviewerlist[1].Content as UCImgViewer).Width = int.Parse(viewerlist.Where(v => v.GetAttribute("name") == "bottom2").FirstOrDefault()?.GetAttribute("width"));
                (bottomscrollviewerlist[2].Content as UCImgViewer).Width = int.Parse(viewerlist.Where(v => v.GetAttribute("name") == "bottom3").FirstOrDefault()?.GetAttribute("width"));
            }





            Loaded -= Page_Loaded;

        }



        private void PageImageView_ScrollChanged(object sender, ScrollChangedEventArgs e)
        {

            currentimgindexCtl.Width = (int)e.VerticalOffset;


        }

        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            MenuItem mnu = sender as MenuItem;
            Image image = null;
            if (mnu != null)
            {
                image = ((ContextMenu)mnu.Parent).PlacementTarget as Image;
            }
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "Bmp (*.bmp)|*.bmp";
            saveFileDialog.RestoreDirectory = true;

            if (saveFileDialog.ShowDialog() == true)
            {
                File.WriteAllText(saveFileDialog.FileName, saveFileDialog.FileName);
                var encoder = new BmpBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create((BitmapSource)image.Source));
                using (FileStream stream = new FileStream(saveFileDialog.FileName, FileMode.Create))
                    encoder.Save(stream);
            }

        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            scrollViewers[0].ScrollToVerticalOffset(0);
        }

        private void C1ComboBox_SelectedItemChanged(object sender, C1.WPF.PropertyChangedEventArgs<object> e)
        {
            searchbatchbtn.Focus();
        }



        private void C1ComboBox_SelectedIndexChanged(object sender, C1.WPF.PropertyChangedEventArgs<int> e)
        {
            searchbatchbtn.Focus();

        }

        private void imageview4_MouseUp(object sender, MouseButtonEventArgs e)
        {
            //if (imageview4.Items.Count == 0)
            //    return;
            //var viewRowCount = imageview4.ActualHeight / 45;

            //var scrollviewer = VisualTreeHelper.GetChild(VisualTreeHelper.GetChild(this.imageview4, 0), 0) as ScrollViewer;
            //var percent = scrollviewer.VerticalOffset / imageview4.Items.Count;
            //var selectindex = Math.Min((int)(scrollviewer.VerticalOffset + viewRowCount * percent), imageview4.Items.Count - 1);
            //imageview4.SelectedIndex = selectindex;
        }

        private void UCImgViewer_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {

        }

        private void ScrollViewer_PreviewMouseWheel(object sender, MouseWheelEventArgs e)
        {
            e.Handled = true;
            var scrollviewer = (sender as ScrollViewer);
            var oraginoffset = scrollviewer.HorizontalOffset;
            (sender as ScrollViewer).ScrollToHorizontalOffset(Math.Max(0, Math.Min(oraginoffset + e.Delta, scrollviewer.ScrollableWidth)));

        }

        private void StackPanel_RequestBringIntoView(object sender, RequestBringIntoViewEventArgs e)
        {
            e.Handled = true;
        }
        UCImgViewer CurrentViewer;//被双击的Viewer，会在浮动窗口中显示，记录下来
        private void UCImgViewer_PreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if ((Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)//就是这一块
            {
                floatingimgviewer.ImageInfo = (sender as UCImgViewer).ImageInfo;
                floatviewer.Visibility = Visibility.Visible;
                CurrentViewer = sender as UCImgViewer;
            }
        }

        private void CloseButton_Click(object sender, RoutedEventArgs e)
        {
            floatviewer.Visibility = Visibility.Collapsed;
        }


        private void GoToPreviousFlowID(object sender, RoutedEventArgs e)
        {
            clist.SelectedIndex = Math.Max(0, clist.SelectedIndex - 1);
            floatingimgviewer.ImageInfo = CurrentViewer.ImageInfo; 
        }

        private void GoToNextFlowID(object sender, RoutedEventArgs e)
        {
            clist.SelectedIndex = Math.Min(clist.Items.Count - 1, clist.SelectedIndex + 1);
            floatingimgviewer.ImageInfo = CurrentViewer.ImageInfo;
        }

        private void surfaceview1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if(floatingimgviewer.Visibility == Visibility.Visible)
            {
                floatingimgviewer.ImageInfo = CurrentViewer?.ImageInfo;
            }
        }
    }
    public class Panodata
    {
        Rect imgRect;
        public Panodata()
        {
            imgRect = new Rect();
        }

    }

    public class ImageContextMenu : ContextMenu
    {
        public ImageContextMenu()
        {
            this.Items.Add(new MenuItem()
            {

            });
        }

    }

}
